var express = require('express');
var router = express.Router();
const acountMoudel = require('../module/bookmodule');
const moment = require('moment'); 
const checkTokenMiddleWare = require('../module/checkTokenMiddleWare'); 



/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});



router.get('/account/list', checkTokenMiddleWare,function(req, res, next) {

  acountMoudel.find().then((data)=>{
    data.forEach((item)=>{
        item.time = moment(item.time).format('YYYY-MM-dd');
    });

    res.send({
      code : 200 ,
      msg : '查询成功',
      data : data 
    });
  }).catch((err)=>{
      res.send({
        code : 500 ,
        msg : err,
        data : {}
      });
        console.log(err);
    });

});

// 新增
router.post('/account/add', function(req, res, next) {
  console.log(req.body);
  // db.get('accounts').push(req.body).write();
  acountMoudel.create(req.body).then((data)=>{
    res.send({
      code : 200 ,
      msg : '添加成功',
      data : data
    });
  }).catch((err)=>{
      console.log(err);
      res.send({
        code : 500 ,
        msg : err,
        data : {}
      });
  });

});

// 修改
router.post('/account/edit', function(req, res, next) {
  console.log(req.body);
  acountMoudel.updateOne({'_id':req.body._id},req.body).then((data)=>{
    res.send({
      code : 200 ,
      msg : '修改成功',
      data : data
    });
  }).catch((err)=>{
      console.log(err);
      res.send({
        code : 500 ,
        msg : err,
        data : {}
      });
  });
});

// 删除 
router.get('/account/:id', function(req, res, next) {
  console.log(req.params);
  db.get('accounts').remove({id:req.params.id}).write();
  res.send("已删除");
});


module.exports = router;
